package com.yiwei.zhh.impl;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.yiwei.zhh.http.ResponseListener;
import com.yiwei.zhh.model.ChsiLoginModel;
import com.yiwei.zhh.util.JsonUtil;
import com.yiwei.zhh.util.PreferenceUtils;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.http.CallBackListener;
import com.yiwei.zhh.http.InterfaceServer;
import com.yiwei.zhh.http.VolleySingleton;
import com.yiwei.zhh.interfaces.ChsiInfo;
import com.yiwei.zhh.http.InfoCallBack;
import com.yiwei.zhh.model.ChsiModel;
import com.yiwei.zhh.model.ChsiPwdModel;
import com.yiwei.zhh.model.RequestModel;
import com.yiwei.zhh.model.ResponseModel;
import com.yiwei.zhh.util.RBLog;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


/**
 * 学信网
 */
public class ChsiInfoImpl implements ChsiInfo {

    private static final int TIME_OUT = 60 * 1000;

    public void getChsiCodeInfo(Context paramContext, String username, String password, final InfoCallBack callBack) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("username", username);
        localHashMap.put("password", password);
        RequestModel model = new RequestModel(localHashMap);

        InterfaceServer.getInstance(paramContext.getApplicationContext()).requestInterface(Const.CAPTCHA, Const.RequestMethod.POST, model, TIME_OUT, new CallBackListener<ChsiModel>(ChsiModel.class, callBack));
//                new ResponseListener() {
//            public void onFinishInMainThread(Object paramAnonymousObject) {
//            }
//
//            public void onStartInMainThread(Object paramAnonymousObject) {
//                callBack.onFailure(paramAnonymousObject.toString());
//            }
//
//            @Override
//            public void onSuccessInMainThread(int paramAnonymousInt, String paramAnonymousString, Object result) {
//                try {
//                    ChsiModel model = (ChsiModel) result;
//                    if (model.getStatus() == 1)
//                        callBack.onSuccess(model.getMsg());
//                    else {
//                        callBack.onFailure(model.getMsg());
//                    }
//                    //返回数据接口
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public Object onSuccessInRequestThread(int statusCode, String content) {
//                try {
//                    return JsonUtil.<ChsiModel>fromJson(content, ChsiModel.class);
//                } catch (Exception e) {
//                    return null;
//                }
//            }
//        });
    }

    public void getChsiInfo(Context paramContext, String username, String password, String captcha, final ChsiCallBack callBack) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("username", username);
        localHashMap.put("password", password);
        localHashMap.put("captcha", captcha);
        RequestModel model = new RequestModel(localHashMap);
        InterfaceServer.getInstance(paramContext.getApplicationContext()).requestInterface(Const.XUE_XIN, Const.RequestMethod.POST, model, TIME_OUT,
                new ResponseListener() {
                    public void onFinishInMainThread(Object paramAnonymousObject) {
                    }

                    public void onStartInMainThread(Object paramAnonymousObject) {
                        callBack.getChsiLoginFail(paramAnonymousObject.toString());
                    }

                    @Override
                    public void onSuccessInMainThread(int paramAnonymousInt, String paramAnonymousString, Object result) {
                        try {
                            ChsiLoginModel model = (ChsiLoginModel) result;
                            if (model.getStatus() == 1) {
                                callBack.getChsiLoginSuccess(model);
                            } else if (model.getStatus() == 2) {
                                callBack.getChsiNeedCode(model.captchaImage);
                            } else {
                                callBack.getChsiLoginFail(model.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public Object onSuccessInRequestThread(int statusCode, String content) {
                        try {
                            return JsonUtil.<ChsiLoginModel>fromJson(content, ChsiLoginModel.class);
                        } catch (Exception e) {
                            return null;
                        }
                    }
                });
    }


    /**
     * 图形验证码
     *
     * @param mContext
     * @param callBack
     */
    @Override
    public void getChsiImgCodeInfo(Context mContext, final InfoCallBack callBack) {
        HashMap map = new HashMap();
        RequestModel model = new RequestModel(map);

        InterfaceServer.getInstance(mContext.getApplicationContext()).requestInterface(Const.CAPTCHA2, Const.RequestMethod.POST, model, TIME_OUT, new CallBackListener<ChsiModel>(ChsiModel.class, callBack));
//                new ResponseListener() {
//            public void onFinishInMainThread(Object paramAnonymousObject) {
//            }
//
//            public void onStartInMainThread(Object object) {
//                callBack.onFailure(object.toString());
//            }
//
//            @Override
//            public void onSuccessInMainThread(int paramAnonymousInt, String paramAnonymousString, Object result) {
//                try {
//                    ChsiModel model = (ChsiModel) result;
//                    if (model.getStatus() == 1)
//                        callBack.onSuccess(model.getCaptcha());
//                    else {
//                        callBack.onFailure(model.getMsg());
//                    }
//                    //返回数据接口
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public Object onSuccessInRequestThread(int statusCode, String content) {
//                try {
//                    return JsonUtil.<ChsiModel>fromJson(content, ChsiModel.class);
//                } catch (Exception e) {
//                    return null;
//                }
//            }
//        });
    }

    /**
     * 找回密码类型
     *
     * @param mContext
     * @param username
     * @param captcha
     * @param callBack
     */
    @Override
    public void getChsiPwdTypeInfo(Context mContext, String username, String captcha, final InfoCallBack callBack) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("username", username);
        localHashMap.put("captcha", captcha);
        RequestModel model = new RequestModel(localHashMap);
        InterfaceServer.getInstance(mContext.getApplicationContext()).requestInterface(Const.RETRIEVE_PWD, Const.RequestMethod.POST, model, TIME_OUT, new CallBackListener<ChsiPwdModel>(ChsiPwdModel.class, callBack));
//                new ResponseListener() {
//            public void onFinishInMainThread(Object paramAnonymousObject) {
//            }
//
//            public void onStartInMainThread(Object paramAnonymousObject) {
//                callBack.onFailure(paramAnonymousObject.toString());
//            }
//
//            @Override
//            public void onSuccessInMainThread(int paramAnonymousInt, String paramAnonymousString, Object result) {
//                try {
//                    ChsiPwdModel model = (ChsiPwdModel) result;
//                    callBack.onSuccess(model);
//                    //返回数据接口
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public Object onSuccessInRequestThread(int statusCode, String content) {
//                try {
//                    return JsonUtil.<ChsiPwdModel>fromJson(content, ChsiPwdModel.class);
//                } catch (Exception e) {
//                    return null;
//                }
//            }
//        });
    }

    /**
     * 邮箱找回密码
     *
     * @param mContext
     * @param ctoken
     * @param email
     * @param realname
     * @param idno
     * @param callBack
     */
    @Override
    public void getRetrieveByEmailInfo(Context mContext, String ctoken, String email, String realname, String idno, final InfoCallBack callBack) {
        HashMap map = new HashMap();
        map.put("ctoken", ctoken);
        map.put("email", email);
        map.put("name", realname);
        map.put("idno", idno);
        RequestModel model = new RequestModel(map);
        InterfaceServer.getInstance(mContext.getApplicationContext()).requestInterface(Const.RETRIEVE_BY_EMAIL, Const.RequestMethod.POST, model, TIME_OUT, new CallBackListener<ChsiModel>(ChsiModel.class, callBack));
//                new ResponseListener() {
//            public void onFinishInMainThread(Object paramAnonymousObject) {
//            }
//
//            public void onStartInMainThread(Object paramAnonymousObject) {
//                callBack.onFailure(paramAnonymousObject.toString());
//            }
//
//            @Override
//            public void onSuccessInMainThread(int paramAnonymousInt, String paramAnonymousString, Object result) {
//                try {
//                    ChsiModel model = (ChsiModel) result;
//                    callBack.onSuccess(model);
//                    //返回数据接口
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public Object onSuccessInRequestThread(int statusCode, String content) {
//                try {
//                    return JsonUtil.<ChsiModel>fromJson(content, ChsiModel.class);
//                } catch (Exception e) {
//                    return null;
//                }
//            }
//        });
    }

    /**
     * 手机找回密码
     *
     * @param mContext
     * @param ctoken
     * @param mobile
     * @param realname
     * @param idno
     * @param captcha
     * @param callBack
     */
    @Override
    public void getRetrieveByPhoneInfo(Context mContext, String ctoken, String mobile, String realname, String idno, String captcha, final InfoCallBack callBack) {
        HashMap map = new HashMap();
        map.put("ctoken", ctoken);
        map.put("mobile", mobile);
        map.put("name", realname);
        map.put("idno", idno);
        map.put("captcha", captcha);
        RequestModel model = new RequestModel(map);
        InterfaceServer.getInstance(mContext.getApplicationContext()).requestInterface(Const.RETRIEVE_BY_PHONE, Const.RequestMethod.POST, model, TIME_OUT, new CallBackListener<ChsiModel>(ChsiModel.class, callBack));
//                new ResponseListener() {
//            public void onFinishInMainThread(Object paramAnonymousObject) {
//            }
//
//            public void onStartInMainThread(Object paramAnonymousObject) {
//                callBack.onFailure(paramAnonymousObject.toString());
//            }
//
//            @Override
//            public void onSuccessInMainThread(int paramAnonymousInt, String paramAnonymousString, Object result) {
//                try {
//                    ChsiModel model = (ChsiModel) result;
//                    callBack.onSuccess(model);
//                    //返回数据接口
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public Object onSuccessInRequestThread(int statusCode, String content) {
//                try {
//                    return JsonUtil.<ChsiModel>fromJson(content, ChsiModel.class);
//                } catch (Exception e) {
//                    return null;
//                }
//            }
//        });
    }

    @Override
    public void getRetrieveByPhoneInfo2(Context mContext, String clst, String vcode, String password, final InfoCallBack callBack) {
        HashMap map = new HashMap();
        map.put("clst", clst);
        map.put("vcode", vcode);
        map.put("password", password);
        RequestModel model = new RequestModel(map);
        InterfaceServer.getInstance(mContext.getApplicationContext()).requestInterface(Const.RESET_PWD_BY_PHONE, Const.RequestMethod.POST, model, TIME_OUT, new CallBackListener<ChsiModel>(ChsiModel.class, callBack));
//                new ResponseListener() {
//            public void onFinishInMainThread(Object paramAnonymousObject) {
//            }
//
//            public void onStartInMainThread(Object paramAnonymousObject) {
//                callBack.onFailure(paramAnonymousObject.toString());
//            }
//
//            @Override
//            public void onSuccessInMainThread(int paramAnonymousInt, String paramAnonymousString, Object result) {
//                try {
//                    ChsiModel model = (ChsiModel) result;
//                    if (model.getStatus() == 1)
//                        callBack.onSuccess(model);
//                    else callBack.onFailure(model.getMsg());
//                    //返回数据接口
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public Object onSuccessInRequestThread(int statusCode, String content) {
//                try {
//                    return JsonUtil.<ChsiModel>fromJson(content, ChsiModel.class);
//                } catch (Exception e) {
//                    return null;
//                }
//            }
//        });
    }


    //*************  学信网 网页API  ***************//

    /**
     * 检查手机号是否存在
     *
     * @param mContext
     * @param mobile
     * @param callBack
     */
    @Override
    public void getCheckMobileInfo(final Context mContext, final String mobile, final InfoCallBack callBack) {
//        HashMap<String, String> hashMap = new HashMap<String, String>();
//        hashMap.put("mphone", mobile);
//        hashMap.put("dataInfo", mobile);
//        hashMap.put("optType", "REGISTER");
//        Gson gson = new Gson();
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(hashMap));
//        okhttp3.Request request = new okhttp3.Request.Builder()
//                .url(Const.CHSI_CHECK_MOBILE)
//                .post(requestBody)
//                .build();
//        OkHttpClientHelper.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.i("dasdsasdadsadas","失败"+e.toString());
//            }
//
//            @Override
//            public void onResponse(Call call, okhttp3.Response response) throws IOException {
//                Log.i("dasdsasdadsadas","成功"+response.toString());
//            }
//        });

        VolleySingleton.getRequestQueue().add(new StringRequest(Request.Method.POST,
                Const.CHSI_CHECK_MOBILE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        callBack.onSuccess(s.trim());
                    }
                }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {
                callBack.onFailure(error.getMessage());
            }
        }) {

            @Override
            protected Response<String> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    Map<String, String> responseHeaders = response.headers;
                    String cookies = responseHeaders.get("Set-Cookie");
                    String dataString = new String(response.data, "UTF-8");
                    RBLog.i("Cokie: ", cookies + "    \n" + dataString);
                    if (!TextUtils.isEmpty(cookies))
                        PreferenceUtils.putString(mContext, "Cookie", cookies);
                    return Response.success(dataString, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }
            }

            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", PreferenceUtils.getString(mContext, "Cookie", ""));

                return headers;
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("mphone", mobile);
                hashMap.put("dataInfo", mobile);
                hashMap.put("optType", "REGISTER");
                return hashMap;
            }

        });
    }

    /**
     * 获取图片验证码
     *
     * @param mContext
     * @param callBack
     */
    @Override
    public void getImgCodeInfo(final Context mContext, final InfoCallBack callBack) {
        VolleySingleton.getRequestQueue().add(new ImageRequest(
                Const.CHSI_CAPTCH_IMAGE,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        callBack.onSuccess(response);
                    }
                }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callBack.onFailure(error.getMessage());
            }
        }) {

            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", PreferenceUtils.getString(mContext, "Cookie", ""));

                return headers;
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("time", System.currentTimeMillis() + "");
                return hashMap;
            }

        });
    }

    @Override
    public void getCodeInfo(final Context mContext, final String mobile, final String captch, final InfoCallBack callBack) {

        VolleySingleton.getRequestQueue().add(new StringRequest(Request.Method.POST,
                Const.CHSI_SMS_CODE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        callBack.onSuccess(s.trim());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callBack.onFailure(error.getMessage());
            }
        }) {

            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", PreferenceUtils.getString(mContext, "Cookie", ""));

                return headers;
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("captch", captch);
                map.put("mobilePhone", mobile);
                map.put("optType", "REGISTER");
                map.put("ignoremphone", "false");
                return map;
            }

        });

    }

    @Override
    public void getRegisterInfo(final Context mContext, final String mobile, final String code, final String realname, final String idno, final String password, final InfoCallBack callBack) {
        VolleySingleton.getRequestQueue().add(new StringRequest(Request.Method.POST,
                Const.CHSI_REGISTER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        callBack.onSuccess(s.trim());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callBack.onFailure(error.getMessage());
            }
        }) {

            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", PreferenceUtils.getString(mContext, "Cookie", ""));

                return headers;
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("from", "chsi-home");
                map.put("mphone", mobile);
                map.put("vcode", code);
                map.put("password", password);
                map.put("password1", password);
                map.put("xm", realname);
                map.put("credentialtype", "SFZ");
                map.put("sfzh", idno);
                return map;
            }

        });
    }
}
